package cn.stylefeng.guns.modular.api.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.modular.bms.entity.BmsPostInfo;
import cn.stylefeng.guns.modular.bms.service.BmsPostInfoService;
import cn.stylefeng.guns.modular.ctm.entity.Ctm;
import cn.stylefeng.guns.modular.ctm.entity.JobApply;
import cn.stylefeng.guns.modular.ctm.entity.JobNotice;
import cn.stylefeng.guns.modular.ctm.service.CtmService;
import cn.stylefeng.guns.modular.ctm.service.JobApplyService;
import cn.stylefeng.guns.modular.ctm.service.JobNoticeService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 投递简历模块管理
 */
@Controller
@RequestMapping("/api/push")
@Api(tags = "数据同步功能")
public class ApiCTMPushController extends BaseController {
    @Autowired
    private CtmService ctmService;
    @Autowired
    private JobNoticeService jobNoticeService;
    @Autowired
    private JobApplyService jobApplyService;
    @Autowired
    private BmsPostInfoService postInfoService;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @RequestMapping(value = "/jobSync", method = RequestMethod.POST)
    @ApiOperation(value = "岗位推送、更新接口", notes = "岗位推送、更新接口")
    public HashMap jobSync(HttpServletRequest req) throws ParseException {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        String data = parameter.get("data").toString();
        JSONObject json = JSONObject.parseObject(data);
        Ctm ctm = JSONObject.parseObject(data, Ctm.class);
        JSONObject enterprise = json.getJSONObject("enterprise");
        if (ObjectUtil.isNotEmpty(enterprise)) {
            ctm.setEnterpriseName(enterprise.getString("enterpriseName"));
            ctm.setInputEnterpriseId(enterprise.getString("inputEnterpriseId"));
            ctm.setUniteCode(enterprise.getString("uniteCode"));
            ctm.setLogo(enterprise.getString("logo"));
            ctm.setScale(enterprise.getString("scale"));
            ctm.setNature(enterprise.getString("nature"));
            ctm.setContents(enterprise.getString("contents"));
        }
        Ctm ctmServiceById = ctmService.getById(ctm);
        ctm.setGwStatus(true);
        if (ObjectUtil.isNotEmpty(ctmServiceById)) {
            log.info("--------------------------修改岗位--------------------------" + ctm.getInputJobId());
            log.info(JSONObject.toJSONString(ctm));
            ctmService.updateById(ctm);
        } else {
            log.info("--------------------------新增岗位--------------------------");
            log.info(JSONObject.toJSONString(ctm));
            ctmService.save(ctm);
        }
        BmsPostInfo bb = new BmsPostInfo();
        bb.setName(ctm.getJobName());
        bb.setSort(1);
        bb.setHot(1);
        bb.setStatus(true);
        bb.setCreateBy("");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        bb.setCreateTime(dateFormat.parse(ctm.getCreateTime()));
        postInfoService.save(bb);
        HashMap dataparams = new HashMap();
        dataparams.put("code", 1);
        dataparams.put("success", true);
        dataparams.put("message", "同步成功");
        HashMap datamap = new HashMap();
        datamap.put("jobId", Integer.parseInt(ctm.getInputJobId()));
        dataparams.put("data", datamap);
        responseparams.put("data", dataparams);
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/jobOffLine", method = RequestMethod.POST)
    @ApiOperation(value = "岗位下架", notes = "岗位下架")
    public HashMap jobOffLine(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        String inputJobId = parameter.get("inputJobId").toString();
        Ctm ctm = ctmService.getById(inputJobId);
        ctm.setGwStatus(false);
        ctmService.updateById(ctm);
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/syncJdBack", method = RequestMethod.POST)
    @ApiOperation(value = "简历状态反馈", notes = "简历状态反馈")
    public HashMap syncJdBack(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        String inputApplyId = parameter.get("inputApplyId").toString();
        String applyStatus = parameter.get("applyStatus").toString();
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/jobNoticeSync", method = RequestMethod.POST)
    @ApiOperation(value = "岗位公告上传", notes = "岗位公告上传")
    public HashMap jobNoticeSync(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        JobNotice jobNotice = JSON.parseObject(JSON.toJSONString(parameter), JobNotice.class);
        // 内容转义
        jobNotice.setNoContent(escape(jobNotice.getNoContent()));
        JobNotice byId = jobNoticeService.getById(jobNotice.getNoInputId());
        if (ObjectUtil.isNotEmpty(byId)) {
            log.info("--------------------------修改公告--------------------------" + byId.getNoInputId());
            log.info(JSONObject.toJSONString(jobNotice));
            jobNoticeService.updateById(jobNotice);
        } else {
            log.info("--------------------------新增公告--------------------------");
            log.info(JSONObject.toJSONString(jobNotice));
            jobNoticeService.save(jobNotice);
        }
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/pushDailyData", method = RequestMethod.POST)
    @ApiOperation(value = "平台统计数据上传", notes = "平台统计数据上传")
    public HashMap pushDailyData(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        String qzvisitnums = parameter.get("qzvisitnums").toString();
        String qzloginnums = parameter.get("qzloginnums").toString();
        String qzlinknums = parameter.get("qzlinknums").toString();
        String qzpostnums = parameter.get("qzpostnums").toString();
        String qyregisternums = parameter.get("qyregisternums").toString();
        String gwnums = parameter.get("gwnums").toString();
        String zwnums = parameter.get("zwnums").toString();
        String source = parameter.get("source").toString();
        String qzlinkmans = parameter.get("qzlinkmans").toString();
        String qzpostmans = parameter.get("qzpostmans").toString();
        String qzinterviewmans = parameter.get("qzinterviewmans").toString();
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/pushApplyData", method = RequestMethod.POST)
    @ApiOperation(value = "平台求职者交易数据上传", notes = "平台求职者交易数据上传")
    public HashMap pushApplyData(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        String unitecode = parameter.get("unitecode").toString();
        String idcardno = parameter.get("idcardno").toString();
        String rdate = parameter.get("rdate").toString();
        String status = parameter.get("status").toString();
        String source = parameter.get("source").toString();
        String jobname = parameter.get("jobname").toString();
        String telephone = parameter.get("telephone").toString();
        String idcardname = parameter.get("idcardname").toString();
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/jobApply", method = RequestMethod.POST)
    @ApiOperation(value = "报名或者取消报名信息接收", notes = "报名或者取消报名信息接收")
    public HashMap jobApply(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        JobApply jobApply = JSON.parseObject(JSON.toJSONString(parameter), JobApply.class);
        jobApplyService.save(jobApply);
        return responseparams;
    }

    @ResponseBody
    @RequestMapping(value = "/jobNotification", method = RequestMethod.POST)
    @ApiOperation(value = "岗位通知", notes = "岗位通知")
    public HashMap jobNotification(HttpServletRequest req) {
        HashMap params = check(req);
        HashMap parameter = (HashMap) params.get("parameter");
        HashMap responseparams = (HashMap) params.get("responseparams");
        String odata = parameter.get("odata").toString();
        JSONArray jsonArray = JSONArray.parseArray(odata);
        return responseparams;
    }

    private HashMap check(HttpServletRequest req) {
        HashMap params = new HashMap();
        HashMap headparams = new HashMap();
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            if (StringUtils.isNotBlank(headerValue)) {
                headparams.put(headerName, headerValue);
            }
        }
        String appkey = headparams.get("appkey").toString();
        String requesttime = headparams.get("requesttime").toString();
        String accesstoken = headparams.get("accesstoken").toString();

        Enumeration<String> parameters = req.getParameterNames();
        HashMap parameter = new HashMap();
        while (parameters.hasMoreElements()) {
            String parameterStr = parameters.nextElement();
            String value = req.getParameter(parameterStr);
            if (StringUtils.isNotBlank(value)) {
                parameter.put(parameterStr, value);
            }
        }
        log.info(parameter.toString());

        HashMap responseparams = new HashMap();
        if (!checksign(appkey, requesttime, accesstoken)) {
            responseparams.put("code", "-1");
            responseparams.put("message", "签名效验失败");
            responseparams.put("success", false);
            return responseparams;
        }
        responseparams.put("code", "1");
        responseparams.put("message", "成功");
        responseparams.put("success", true);
        params.put("headparams", headparams);
        params.put("parameter", parameter);
        params.put("responseparams", responseparams);
        return params;
    }

    public static Boolean checksign(String appKey, String requestTime, String accessToken) {
        System.out.println(appKey + requestTime + accessToken);
        Boolean flag = false;
        String appSecret = "6fb1c577-ae56-4cea-beea-161ed4113f27";
        //本地签名
        String accessTokennew = MD5(appKey + requestTime + appSecret);
        if (accessTokennew.equals(accessToken)) {
            flag = true;
        }
        return flag;
    }

    public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();


        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }

    private String escape(String content) {
        Pattern regex = Pattern.compile("&\\s[a-z]*;");
        Pattern regex1 = Pattern.compile("&\\s#[0-9]*;");
        Matcher matcher = regex.matcher(content);
        Matcher matcher1 = regex1.matcher(content);
        while (matcher.find()) {
            String group = matcher.group();
            String s = matcher.group().replaceAll(" ", "");
            content = content.replaceAll(group, s);
        }
        while (matcher1.find()) {
            String group = matcher1.group();
            String s = matcher1.group().replaceAll(" ", "");
            content = content.replaceAll(group, s);
        }
        return StringEscapeUtils.unescapeHtml(StringEscapeUtils.unescapeHtml(content));
    }

//    public static void main(String[] args) {
//        String appSecret = "6fb1c577-ae56-4cea-beea-161ed4113f27";
//        String appKey = "3416f085-e510-4420-90ce-bebf808a03fe";
//        String requestTime = "1717379705";
////        System.currentTimeMillis();
//// 方法二
////        String requestTime=  Calendar.getInstance().getTimeInMillis()+"";
//// 方法三
////       System.out.println(new Date().getTime()+"");*//*
//        //本地签名
//        String accessTokennew = MD5(appKey + requestTime + appSecret);
//        System.out.println(accessTokennew);
//    }

}



